/*
 *
 *  AutoWallpaper (Android) Version 1.x
 *  Copyright (C) 2010 - 2011, Tyler H. Jones (me@tylerjones.me)
 *  http://www.autowallpaper.org/
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */


package com.tylerhjones.autowallpaper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ImageManager extends Activity {
	
///*****************************************************************************************//
///*** onCreate function, beginning of AutoWallpaperActivity                             ***//
///*****************************************************************************************//	   
	
	private static final String TAG = "ImageManager";
	public boolean testVar;
	protected TextView lblListInfo;
	protected ListView lstImages;
	public Uri imageUri = null;
	public Uri imgManagerUri = null;
	protected List<String> Images = new ArrayList<String>();
	@SuppressWarnings("unused")
	private AWService AWS;
	private AWCore Core;
	
	private static final int DIALOG_ADDALLDIRS_ID = 1;
	private static final int DIALOG_ADDFOLDER_ID = 2;
	private static final int DIALOG_BROKEN_ID = 3;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Core = new AWCore(this);
        setContentView(R.layout.images_manager);
        
        lblListInfo = (TextView) findViewById(R.id.lblListInfo);
        lstImages = (ListView) findViewById(R.id.lstImages);
        lstImages.setOnItemClickListener(mMessageClickedHandler); 
        registerForContextMenu(lstImages); 
        lblListInfo.setText("Total Images: " + String.valueOf(Images.size())); 
	}
	
	
    @Override
    public void onStart() {
    	super.onStart();
        doBindService();
        Images = Core.getAllImages();
        lblListInfo.setText("Total Images: " + String.valueOf(Images.size()));
    	setImages(Images);
    }
    
///*****************************************************************************************//
///*** General FUnctions and Methods                                                     ***//
///*****************************************************************************************//
	
    @Override
    public void onDestroy() {
    	super.onDestroy();
    	Images.clear();
    	//doUnbindService();
    }
    
    @Override
    public void onStop() {
    	super.onStop();
    	Images.clear();
    	doUnbindService();
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	Images.clear();
    	Images = Core.getAllImages();
        lblListInfo.setText("Total Images: " + String.valueOf(Images.size()));
    	setImages(Images);
    }
    
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
      if (v.getId()==R.id.lstImages) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
        menu.setHeaderTitle(Images.get(info.position));
        String[] menuItems = getResources().getStringArray(R.array.lstImages_contextmenu);
        for (int i = 0; i<menuItems.length; i++) {
          menu.add(Menu.NONE, i, i, menuItems[i]);
        }
      }
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
      boolean res = true;
      AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
      int menuItemIndex = item.getItemId();
      String[] menuItems = getResources().getStringArray(R.array.lstImages_contextmenu);
      String listItemName = Images.get(info.position);
      switch(menuItemIndex) {
      	case 0:
        ShowImageInfo(listItemName);
    	break;
      	case 1:
      	res = Core.removeImage(listItemName);
      	if(res) { 
      		Images = Core.getAllImages(); 
	        lblListInfo.setText("Total Images: " + String.valueOf(Images.size()));
	  		setImages(Images);
      	}
      	case 2:
      		File f = new File(listItemName);
    		try {
    			Core.SetWallpaper(f);
    		} catch (Exception e) {
    			Log.e(TAG, "File not found when executing SetWallpaper()");
    			e.printStackTrace();
    		}
        break;
        default:
        break;
      }
      
      return res;
    }
	
    protected Dialog onCreateDialog(int id) {
        Dialog adialog = null;
        switch(id) {
        case DIALOG_ADDALLDIRS_ID:
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
        	builder.setMessage(getText(R.string.addfileorfolder_msg_body))
        		   .setTitle(getText(R.string.addfileorfolder_msg_title))
        	       .setCancelable(false)
        	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        	    	   @Override
        	           public void onClick(DialogInterface dialog, int id) {
        	    		   lblListInfo.setText("Current Dir:" + imageUri.getPath());
        	           }
        	       })
        	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
        	    	   @Override
        	           public void onClick(DialogInterface dialog, int id) {
        	                dialog.cancel();
        	           }
        	       });
        	AlertDialog alert = builder.create();
        	adialog = alert;
            break;
        case DIALOG_BROKEN_ID:
        	AlertDialog.Builder bbuilder = new AlertDialog.Builder(this);
        	bbuilder.setMessage(getText(R.string.wompwomp_body))
        		   .setTitle(getText(R.string.wompwomp_title))
        	       .setCancelable(false)
        	       .setNegativeButton("Womp womp...", new DialogInterface.OnClickListener() {
        	    	   @Override
        	           public void onClick(DialogInterface dialog, int id) {
        	                dialog.cancel();
        	           }
        	       });
        	AlertDialog salert = bbuilder.create();
        	adialog = salert;
            break;
        case DIALOG_ADDFOLDER_ID:
        	AlertDialog.Builder folderDialog = new AlertDialog.Builder(this);

        	//folderDialog.setTitle("Title");
        	folderDialog.setMessage("Add all images in folder:");

        	final EditText txtFolderPath = new EditText(this);
        	folderDialog.setView(txtFolderPath);
        	txtFolderPath.setText("/mnt/sdcard/Pictures");

        	folderDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int whichButton) {
        	  String value = txtFolderPath.getText().toString();
        	  	File dir = new File(value);
        	  	if(!dir.isDirectory()) {
        	  		Toast.makeText(getApplicationContext(), "Directory '" + value + "' not found!", Toast.LENGTH_LONG).show();
        	  	} else {
        	  		File[] imgs = dir.listFiles(new FilenameFilter(){  
        	  			@Override  
        	  			public boolean accept(File dir, String name)  
        	  			{  
        	  				return ((name.endsWith(".jpg"))||(name.endsWith(".png")));
        	  			}  
        	  		});
        	  		Core.addImages(imgs);
        	  		Images = Core.getAllImages();
        	        lblListInfo.setText("Total Images: " + String.valueOf(Images.size()));
        	  		setImages(Images);
        	  	}
        	  }
        	});

        	folderDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        	  public void onClick(DialogInterface dialog, int whichButton) {
        	    // Canceled.
        	  }
        	});
        	
        	folderDialog.show();

            break;
        default:
            adialog = null;
            break;
        }
        return adialog;
    }
    
    public void setImages(List<String> imgs) {
    	String[] arrayImages = new String[imgs.size()];
    	imgs.toArray(arrayImages);
    	ItemsAdapter adapter = new ItemsAdapter(this, R.id.listitem_filename, arrayImages);
    	lstImages.setAdapter(adapter);
        Log.v("ImageManager", "ImageManager.setImages() was called!");
		//Toast.makeText(getApplicationContext(), "Cross-activity communication WORKS!", Toast.LENGTH_LONG).show();
    }
    
    public void ShowImageInfo(final String imgfile) {
    	final Dialog imageinfo = new Dialog(ImageManager.this);
    	imageinfo.setContentView(R.layout.imginfo_dialog);
    	imageinfo.setTitle("Image Info");
    	imageinfo.setCancelable(true);
        //Setup textview
        TextView text = (TextView) imageinfo.findViewById(R.id.lblImageInfoFilename);
        text.setText("Image File: " + imgfile);

        //Setup image view
        ImageView img = (ImageView) imageinfo.findViewById(R.id.image_preview);
        img.setImageBitmap(Core.decodeFile(new File(imgfile), 120, 120));

        //Setup buttons
        Button btnImageInfoClose = (Button) imageinfo.findViewById(R.id.btnImageInfoClose);
        btnImageInfoClose.setOnClickListener(new OnClickListener() {
        @Override
            public void onClick(View v) {
        		imageinfo.dismiss();
            }
        });
        Button btnImageInfoRemove = (Button) imageinfo.findViewById(R.id.btnImageInfoRemove);
        btnImageInfoRemove.setOnClickListener(new OnClickListener() {
        @Override
            public void onClick(View v) {
        		imageinfo.dismiss();
        		boolean res = Core.removeImage(imgfile);
              	if(res) { 
              		Images = Core.getAllImages(); 
        	        lblListInfo.setText("Total Images: " + String.valueOf(Images.size()));
        	  		setImages(Images);
              	}
        		
            }
        });
        Button btnImageInfoSetCurrent = (Button) imageinfo.findViewById(R.id.btnImageInfoSetCurrent);
        btnImageInfoSetCurrent.setOnClickListener(new OnClickListener() {
        @Override
            public void onClick(View v) {
        		imageinfo.dismiss();
        		File f = new File(imgfile);
        		try {
        			Core.SetWallpaper(f);
        		} catch (Exception e) {
        			Log.e(TAG, "File not found when executing SetWallpaper()");
        			e.printStackTrace();
        		}
            }
        });
        
        //now that the dialog is set up, it's time to show it    
        imageinfo.show();
    }
    
///*****************************************************************************************//
///*** Event handler functions                                                           ***//
///*****************************************************************************************//
    
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	super.onCreateOptionsMenu(menu);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.imgman_menu, menu);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.mnuImgmanAddGallery:
        	//new ViewGalleryTask().execute("");
        	showDialog(DIALOG_BROKEN_ID);
            return true;
        case R.id.mnuImgmanAddFolder:
        	showDialog(DIALOG_ADDFOLDER_ID);
            return true;
        case R.id.mnuImgmanVerify:
        	Core.ValidateDBImages(Images);
            return true;
        case R.id.mnuImgmanRemoveAll:
        	boolean res = Core.removeAllImages();
        	Images.clear();
	        lblListInfo.setText("Total Images: 0");
	        lstImages.setAdapter(null);
            return res;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    protected void onActivityResult(final int requestCode, int resultCode, final Intent data) { 	
    	if(resultCode == Activity.RESULT_OK) {
    		switch(requestCode) {
    			case Common.GALLERY_IMAGE_REQUEST_CODE:
    				imageUri = data.getData();
    				Log.d("ImageManager.onActivityResult", "imgsrc: " + imageUri.getPath() + "  --  imgfile: " + imageUri.toString());
    				File[] files = new File[1];
    				files[0] = new File(imageUri.getPath());
    				Core.addImages(files);
    	 			break;

    			case Common.IMAGE_MANAGER_REQUEST_CODE:
    				imgManagerUri = data.getData();
    				Log.d("ImageManager.onActivityResult", "imgsrc: " + imgManagerUri.getPath() + "  --  ReturnCmd: " + imgManagerUri.toString());
    	 			break;    	 		

    	 		default:
    	 			Log.w("ImageManager.onActivityResult", "An activity finished and it wasn't recognized by the select-case statement.");
    	 			break;
    		}
    	}
    }
    
   
///*****************************************************************************************//
///*** Service binding/connection handling                                               ***//
///*****************************************************************************************//
    
      private ServiceConnection svcConnection = new ServiceConnection() {
          public void onServiceConnected(ComponentName className, IBinder service) {
          	try {
  	        	Log.d("### nServiceConnected", "Service is being started...");
  	        	AWS = ((AWService.LocalBinder)service).getService();
  	        	Log.d("### onServiceConnected", "AWS object value set..");
  	            //Toast.makeText(AutoWallpaperActivity.this, getText(R.string.service_conn_notif), Toast.LENGTH_SHORT).show();
  	        	Images = Core.getAllImages();
  	        	setImages(Images);
  	        	lblListInfo.setText("Total Images: " + String.valueOf(Images.size()));
  	            Log.d("### onServiceConnected", "Service startup complete.");
      		} catch (Exception e) {
      		    Log.e("### onServiceConnected", "Error in onServiceConnected", e);
      		}
          }
          
          public void onServiceDisconnected(ComponentName className) {
          	AWS = null;
          	Log.w(TAG, "Service was disconnected! Might be intentional, might not be...");
          }
      };

      void doBindService() {
      	Thread t = new Thread(){
      		public void run(){
              	Log.d("doBindService", "Binding thread started...");
      			boolean res = bindService(new Intent(ImageManager.this, AWService.class), svcConnection, Context.BIND_AUTO_CREATE);
      			String str;
      			if(res) { str = "TRUE"; } else { str = "FALSE"; }
      			Log.d("doBindService", "Service is bound. bindService(...) Result: " + str);
      		}
      	};
      	t.start();
        //Toast.makeText(getApplicationContext(), getText(R.string.toastworks), Toast.LENGTH_SHORT).show();
      }

      void doUnbindService() {
              unbindService(svcConnection);
      }
    
   
 ///*****************************************************************************************//
 ///*** Private Classes                                                                   ***//
 ///*****************************************************************************************//  

    private class ViewGalleryTask extends AsyncTask<String, String, String> {

    	private Intent getImageFromGalleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    	
    	@Override
        protected void onPreExecute() {
    		Log.d("ViewGalleryTask", "Pre-execute.");
        }

    	@Override
        protected String doInBackground(final String... args) {
        	ImageManager.this.startActivityForResult(getImageFromGalleryIntent, Common.GALLERY_IMAGE_REQUEST_CODE);
        	return "OK";
        }

    	@Override
        protected void onPostExecute(final String unused) {
    		Log.d("ViewGalleryTask", "Post-execute.");
        }
     }

    private class ItemsAdapter extends BaseAdapter {
    	  String[] items;

    	  public ItemsAdapter(Context context, int textViewResourceId, String[] items) {
    	   this.items = items;
    	  }

    	  @Override
    	  public View getView(final int position, View convertView, ViewGroup parent) {
    		  TextView txtInfo;
    		  TextView txtFilename;
    		  View view = convertView;
    		  ImageView imgImage;
    		  if (view == null) {
    			  LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    			  view = vi.inflate(R.layout.imagelist_item, null);
    		  }
    		  txtFilename = (TextView) view.findViewById(R.id.listitem_filename);
    		  txtInfo = (TextView) view.findViewById(R.id.listitem_info);
    	   
    		  //String filename = items[position].substring(items[position].lastIndexOf("/"));
    		  if(items[position] != null) {
    			  File file = new File(items[position]);
    			  String filename = file.getName();
    			  txtFilename.setText(filename);
    			  double flen = file.length();
    			  String strlen = String.valueOf(flen/1024/1024);
    			  txtInfo.setText("Size: " + strlen.substring(0, strlen.lastIndexOf(".") + 3) + "Mb");  
    		  }	   
    		  return view;
    	  }

    	  public int getCount() {
    	   return items.length;
    	  }

    	  public Object getItem(int position) {
    	   return position;
    	  }

    	  public long getItemId(int position) {
    	   return position;
    	  }

	}
    
    private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
        public void onItemClick(AdapterView parent, View v, int position, long id)
        {
        	ShowImageInfo(Images.get(position));
        }
    };

}
